def encode_rail_fence_cipher(s, n):
    print('endoce:', s, n)
    if s == '':
        return s
    stastics = {}
    i = 0
    d = 1
    if n == 2:
        for x in s:
            stastics[i] = stastics[i]+x if i in stastics.keys() else x
            i = 0 if i else 1
    else:
        for x in s:
            stastics[i] = stastics[i]+x if i in stastics.keys() else x
            i += d
            if i == n:
                i, d = n-2, -1
            elif i == 0:
                d = 1
    out = ''
    for i in range(n):
        out += stastics[i]
    return out


def decode_rail_fence_cipher(s, n):
    print('decode:', s, n)
    if s=='':
        return s
    stastics = {}
    i = 0
    d = 1
    if n == 2:
        for x in s:
            stastics[i] = stastics[i]+1 if i in stastics.keys() else 1
            i = 0 if i else 1
    else:
        for x in s:
            stastics[i] = stastics[i]+1 if i in stastics.keys() else 1
            i += d
            if i == n:
                i, d = n-2, -1
            elif i == 0:
                d = 1
    segments={}
    k=0
    for i in range(n):
        l=stastics[i]
        segments[i]=s[k:k+l]
        k+=l
    out=''
    while len(out)<len(s):
        for i in range(n):
            if segments[i]!='':
                out+=segments[i][0]
                segments[i]=segments[i][1:]

        for i in range(n-2,0,-1):
            if segments[i]!='':
                out+=segments[i][0]
                segments[i]=segments[i][1:]
    return out
